package com.hot.hot_backend.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hot.hot_backend.pojo.HotGoods;
import com.hot.hot_backend.pojo.HotShop;
import com.hot.hot_backend.pojo.Vo;
import com.hot.hot_backend.service.impl.HotGoodsServiceImpl;
import com.hot.hot_backend.service.impl.HotShopServiceImpl;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  购物车
 * </p>
 *
 * @author hot
 * @since 2024-07-17
 */
@CrossOrigin
@RestController
@RequestMapping("/hot_shop")
public class HotShopController {

    @Resource
    private HotShopServiceImpl shopService;

    @Resource
    private HotGoodsServiceImpl goodsService;
    // 新增购物车
    @PostMapping("/insert")
    public Vo<HotShop> insert(@RequestBody HotShop shop){
        // 查询出商品
        LambdaQueryWrapper<HotGoods> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(HotGoods::getId,shop.getSId());
        HotGoods one = goodsService.getOne(wrapper);
        // 判断库存够不够
        if (one.getInventory() >= shop.getCount()){
            one.setInventory(one.getInventory()-shop.getCount());
            // 更新库存
            goodsService.updateById(one);
            boolean b = shopService.save(shop);
            if (b){
                return new Vo<>(b,"新增成功！");
            }else {
                return new Vo<>(b,"新增失败，请稍后重试！");
            }
        }else {
            return new Vo<>(false,"没有这么多库存！");
        }
    }
    // 删除购物车
    @GetMapping("/deleteById/{id}")
    public Vo<HotShop> deleteById(@PathVariable("id") String id){
        UpdateWrapper<HotShop> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",id);
        boolean b = shopService.remove(wrapper);
        if (b){
            return new Vo<>(b,"删除成功！");
        }else {
            return new Vo<>(b,"删除失败，请稍后重试！");
        }
    }
    // 修改购物车数量和金额
    @PostMapping("/updateCount")
    public Vo<HotShop> updateCount(@RequestBody HotShop shop) {
        boolean b = shopService.updateById(shop);
        if (b){
            return new Vo<>(b,"");
        }else {
            return new Vo<>(b,"");
        }
    }

    // 查询每个用户的购物车
    @GetMapping("/queryOne/{id}")
    public Vo<HotShop> queryOne(@PathVariable("id") String uid){
        LambdaQueryWrapper<HotShop> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(HotShop::getUId,uid);
        List<HotShop> list = shopService.list(wrapper);
        if (list.size() > 0){
            return new Vo<>(true,list);
        }else {
            return new Vo<>(false,"目前没有订单！");
        }
    }

}
